package logic

import (
	"box-fresh-api/models/cache"
	"box-fresh-api/models/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"box-fresh-api/boxrpc/boxrpc"
	"box-fresh-api/boxrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *boxrpc.GoodsListRequest) (*boxrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("goodsId_%d", in)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	var list []*boxrpc.GoodList
	if result == "" {
		var err error
		list, err = mysql.GoodList(mysql.DB, in)
		if err != nil {
			return nil, err
		}
		maeshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, maeshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &boxrpc.GoodsListResponse{
		List: list,
	}, nil
}
